package com.github.catvod.spider;

import android.content.Context;

import com.github.catvod.bean.Class;
import com.github.catvod.bean.Result;
import com.github.catvod.bean.Vod;
import com.github.catvod.crawler.Spider;
import com.github.catvod.crawler.SpiderDebug;
import com.github.catvod.net.OkHttp;
import com.github.catvod.utils.ProxyVideo;
import com.github.catvod.utils.Util;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class BedNews extends Spider {
    private static String siteUrl = "https://bad.news/";
    private HashMap<String, String> getHeaders() {
        HashMap<String, String> headers = new HashMap<>();
        headers.put("User-Agent", Util.CHROME);
        return headers;
    }
    @Override
    public String homeContent(boolean filter) throws Exception {
        List<Class> classes = new ArrayList<>();
        String[] typeIdList = {"足","舔屁眼","女王","颜面骑乘","女同"};
        String[] typeNameList = {"足","舔屁眼","女王","颜面骑乘","女同"};
        for (int i = 0; i < typeNameList.length; i++) {
            classes.add(new Class(URLEncoder.encode(typeIdList[i]), typeNameList[i]));
        }
        List<Vod> list = new ArrayList<>();
        return Result.string(classes,list);
    }

    // 开发网络请求代理
    public String request(String url, HashMap<String, String> header){
        try {
            Proxy httpProxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 33210));
            // 获取系统环境代理，后续 使用代理
            Proxy proxy = new OkHttpClient().proxy();
            OkHttpClient client = new OkHttpClient.Builder().proxy(httpProxy).build();
            Request.Builder build = new Request.Builder().url(url);
            // 进行设置请求头
            for (String key : header.keySet()) {
                build.addHeader(key, Objects.requireNonNull(header.get(key)));
            }
            Request req = build.build();
            Response response = client.newCall(req).execute();
            if (response.body() != null) {
                return response.body().string();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return null;
    }
    public String request_local(String url, HashMap<String, String> header){
        try {
            // 获取系统环境代理，后续 使用代理
            Proxy proxy = new OkHttpClient().proxy();
            OkHttpClient client = new OkHttpClient.Builder().proxy(proxy).build();
            SpiderDebug.log("请求地址："+url);
            Request.Builder build = new Request.Builder().url(url);
            // 进行设置请求头
            for (String key : header.keySet()) {
                build.addHeader(key, Objects.requireNonNull(header.get(key)));
            }
            SpiderDebug.log("请求头："+header);
            Request req = build.build();
            Response response = client.newCall(req).execute();
            SpiderDebug.log("请求成功!");
            if (response.body() != null) {
                return response.body().string();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return null;
    }

    private List<Vod> parseVods(Document doc) {
        Elements item_list = doc.select(".link.col-md-4");
        List<Vod> list = new ArrayList<>();
        for (Element item: item_list) {
            String text = item.select(".title").text();
            String pic = item.select(".coverimg img").attr("data-echo");
            String url = item.select(".coverdiv a").attr("href");
            list.add(new Vod(url,text,pic));
        }
        return list;
    }

    // 获取分类内容
    @Override
    public String categoryContent(String tid, String pg, boolean filter, HashMap<String, String> extend) throws Exception {
        String categoryUrl=siteUrl+"av/search/q-"+tid+"/page-"+pg;;
        Notice.show(categoryUrl);
        String response = request_local(categoryUrl, getHeaders());
        Document doc = Jsoup.parse(response);
        List<Vod> list= parseVods(doc);
        Integer total = (Integer.parseInt(pg)+1)*20;
        return Result.string(Integer.parseInt(pg),Integer.parseInt(pg)+1,20,total,list);
    }

    @Override
    public String detailContent(List<String> ids) throws Exception {
        // 进行去除siteUrl最后一个/
        String detailUrl="";
        if (siteUrl.endsWith("/")){
            detailUrl=siteUrl.substring(0, siteUrl.length() - 1)+ids.get(0);
        }
        String response = request_local(detailUrl, getHeaders());
        Document doc = Jsoup.parse(response);
        // 进行获取mate中的封面
        String pic = doc.select("meta[property=og:image]").attr("content");
        String name = doc.select("meta[property=og:title]").attr("content");
        // 描述
        String content = doc.select("meta[name=Description]").attr("content");
        // 获取播放地址
        String playerUrl = doc.select(".my-videos").attr("data-source");
        // 进行获取演员
        String actor = doc.select("div.detail-content p").get(0).select("a").text();
        String tag = doc.select("div.detail-content p").get(1).select("a").text();
        Vod vod = new Vod();
        vod.setVodId(ids.get(0));
        vod.setVodPic(pic);
        vod.setVodName(name);
        vod.setVodContent(content);
        vod.setVodActor(actor);
        vod.setVodTag(tag);
        vod.setVodPlayUrl("在线播放$"+playerUrl);
        vod.setVodPlayFrom("m3u8");
        return Result.string(vod);
    }

    @Override
    public String playerContent(String flag, String id, List<String> vipFlags) throws Exception {
        return Result.get().url(id).header(getHeaders()).string();
    }
}
